<template>
  <div>
    <!-- :title="itemInfo.id ? '编辑设备' : '新增设备'" -->
    <el-dialog
      :visible.sync="dialogVisible"
      width="1200px"
      title="请选择"
      :before-close="closeDialog"
      :close-on-click-modal="false"
      append-to-body
    >
      <div class="content-box">
        <div class="container">
          <div class="header" style="height: 50px">
            <div class="header_left">资源列表</div>
            <div class="header_right">
              <el-select
                v-model="searchForm.buildingId"
                filterable
                clearable
                @clear="clearBuild"
                size="mini"
                placeholder="请选择建筑物"
                style="width: 200px"
                @change="changeBuild"
                v-loadMore="loadMore"
              >
                <el-option
                  v-for="item in buildList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                >
                </el-option>
                <div
                  class="div_box"
                  v-loading="loading"
                  :style="loading ? '' : 'display: none;'"
                ></div>
              </el-select>
              <el-input
                placeholder="请输入设备编码"
                v-model="searchForm.imei"
                style="width: 200px; margin-left: 15px"
                size="mini"
                maxlength="30"
                clearable
                @clear="clearImei"
                class="el_input"
              >
                <el-button
                  slot="append"
                  :icon="loadingSearch ? 'el-icon-loading' : 'el-icon-search'"
                  @click="searchClick"
                >
                </el-button>
              </el-input>
            </div>
          </div>
          <div class="content">
            <el-table
              :data="dataList"
              ref="refTable"
              class="table"
              height="350px"
              :header-cell-style="headerStyle"
              row-key="id"
              @selection-change="batchSelect"
              @select="onSelect"
              :row-selectable="false"
            >
              <el-table-column
                width="45"
                align="center"
                type="selection"
                :reserve-selection="true"
                :selectable="(row) => row.existCount === 0"
              ></el-table-column>
              <!-- <el-table-column
                align="center"
                label="序号"
                type="index"
                width="80"
                height="30"
              ></el-table-column> -->
              <el-table-column
                align="center"
                prop="imei"
                label="设备编码"
                min-width="160"
                show-overflow-tooltip
              ></el-table-column>

              <el-table-column
                align="center"
                prop="spaceName"
                label="安装点"
                min-width="160"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                align="center"
                prop="existCount"
                label="关联其他消控室"
                min-width="160"
                show-overflow-tooltip
              >
                <template slot-scope="scope">
                  <el-tag
                    v-if="scope.row.existCount == 1"
                    type="danger"
                    size="mini"
                    >是</el-tag
                  >
                  <el-tag v-else type="success" size="mini">否</el-tag>
                </template></el-table-column
              >
            </el-table>
            <pagination
              v-show="total > 0"
              :total="total"
              :page.sync="page"
              :limit.sync="limit"
              :pageSizes="[10, 20, 30, 50]"
              @pagination="getDataList"
              class="pagination"
            />
          </div>
        </div>
        <div class="middle-icon">
          <i class="el-icon-arrow-right"></i>
        </div>
        <div class="container">
          <div class="header" style="height: 50px">
            <div class="header_left">
              <span v-if="recordDataList && recordDataList.length > 0"
                >已选列表（{{ recordDataList.length || 0 }}条）</span
              >
            </div>
            <div class="header_right">
              <el-button
                class="el_button"
                size="mini"
                type="danger"
                style="margin-left: 15px"
                @click="onBatchDelete"
              >
                清空
              </el-button>
            </div>
          </div>
          <div class="content">
            <el-table
              :data="recordDataList"
              class="table"
              height="400px"
              row-key="id"
              :header-cell-style="headerStyle"
            >
              <el-table-column
                align="center"
                label="序号"
                type="index"
                width="80"
                height="30"
              ></el-table-column>
              <el-table-column
                align="center"
                prop="imei"
                label="设备编码"
                min-width="200"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column
                align="center"
                prop="spaceName"
                label="安装点"
                min-width="180"
                show-overflow-tooltip
              ></el-table-column>
              <el-table-column align="center" label="操作" min-width="90">
                <template slot-scope="scope">
                  <el-tooltip
                    class="item"
                    effect="dark"
                    content="删除"
                    placement="bottom"
                  >
                    <i
                      @click="onDelete(scope.row)"
                      class="iconfont shanchu tableBtnIcon"
                    ></i>
                  </el-tooltip>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </div>
      </div>
      <div style="margin-top: 6px">注：已经被其他消控室关联的设备不能选择</div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="closeDialog" class="cancel-button"
          >取 消</el-button
        >
        <el-button
          size="small"
          @click="submit"
          v-preventReClick="1000"
          class="confirm-button"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import tableStyleMixin from "@mixin/table-style";
import Pagination from "@components/Pagination.vue";
import { reqDevicePage, reqSpaceManager } from "@api/api.js";
import { mapState } from "vuex";
export default {
  props: ["selectList", "pageType", "orgId"],
  mixins: [tableStyleMixin],
  components: {
    Pagination,
  },
  data() {
    return {
      dialogVisible: false,
      dataList: [],
      total: 0,
      page: 1,
      limit: 10,
      searchForm: {
        imei: "",
        buildingId: "",
      },
      loadingSearch: false,

      buildList: [],
      loading: false,
      sysInstanceIndex: 1,
      sysInstanceTotalPages: 10,

      recordDataList: [],
    };
  },
  computed: {
    ...mapState(["user"]),
  },
  watch: {
    dialogVisible(val) {
      if (val) {
        this.$nextTick(async () => {
          this.recordDataList = this.selectList;
          await this.backDisplayList(true);
          await this.getInitDataList();
          await this.getBuildList();
        });
      }
    },
  },
  methods: {
    // 回显列表
    backDisplayList(flag) {
      if (this.recordDataList.length > 0) {
        this.recordDataList.forEach((item) => {
          this.$refs.refTable.toggleRowSelection(item, flag);
        });
      }
    },
    // 获取建筑物列表
    async getBuildList() {
      let res = await reqSpaceManager(this.sysInstanceIndex, 10, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        orgId: this.orgId,
        metaCode: 1,
        isStatistics: 0,
        include: 1, //是否包含下级0包含 1不包含
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
      this.sysInstanceTotalPages = res.data.total;
      this.buildList = [...this.buildList, ...res.data.rows];
    },
    async loadMore() {
      if (this.sysInstanceIndex >= Math.ceil(this.sysInstanceTotalPages / 10))
        return;
      this.sysInstanceIndex++;
      this.loading = true;
      await this.getBuildList();
      // 获取列表数据的方法
      this.loading = false;
    },
    // 选择建筑物
    changeBuild() {
      this.getInitDataList();
    },
    clearBuild() {
      this.getInitDataList();
    },

    // 获取设备列表
    async getDataList() {
      let { imei, buildingId } = this.searchForm;
      const res = await reqDevicePage(this.page, this.limit, {
        userId: this.user.userId,
        roleName: this.user.roleName,
        tenantId: this.user.tenantId,
        orgId: this.orgId,

        imei,
        buildingId,

        productIdList:
          this.pageType === "normal"
            ? ["1869314101783138305", "1889201549113819137"]
            : ["1503927023020938595"],
      });
      if (res.code !== 20000) return this.$modal.notifyWarning(res.message);

      let { rows } = res.data;

      rows = rows.map((item) => {
        // 如果 existCount 为1 且存在 存在recordDataList（imei一致） 则existCount设置回来 为0
        if (
          item.existCount === 1 &&
          this.recordDataList.some(
            (recordItem) =>
              (recordItem.deviceCode || recordItem.imei) === item.imei
          )
        ) {
          item.existCount = 0;
        }
        return item;
      });
      this.dataList = rows;
      this.total = res.data.total;
      this.dataReplace();
    },
    async getInitDataList() {
      this.page = 1;
      this.limit = 10;
      await this.getDataList();
    },

    async searchClick() {
      this.loadingSearch = true;
      await this.getInitDataList();
      this.loadingSearch = false;
    },

    clearImei() {
      this.getInitDataList();
    },

    // 数据替换
    dataReplace() {
      // this.recordDataList = this.recordDataList.map((recordItem) => {
      //   const matchedItem = this.dataList.find(
      //     (dataItem) => dataItem.imei === recordItem.imei
      //   );
      //   // ✅ 找到匹配项则替换，否则保留原对象
      //   return matchedItem ? matchedItem : recordItem;
      // });
      // this.backDisplayList(true);

      this.recordDataList.forEach((item) => {
        this.dataList.forEach((dataItem) => {
          if (dataItem.imei === item.imei) {
            this.$refs.refTable.toggleRowSelection(item, false);
            this.$refs.refTable.toggleRowSelection(dataItem, true);
          }
        });
      });
    },
    onSelect(selection, row) {
      // console.log("onSelect", selection, row);
    },
    batchSelect(arr) {
      // console.log("batchSelect", arr);
      let batchDataList = arr;

      // 查重
      // batchDataList = batchDataList.filter(
      //   (item, index) =>
      //     batchDataList.findIndex(
      //       (recordItem) => recordItem.imei === item.imei
      //     ) === index
      // );

      this.recordDataList = batchDataList;
    },
    onBatchDelete() {
      this.backDisplayList(false);
      this.recordDataList = [];
    },
    onDelete(row) {
      const { recordDataList } = this;
      this.recordDataList.splice(
        recordDataList.findIndex((item) => item.id === row.id),
        1
      );
      this.$refs.refTable.doLayout();
      this.$nextTick(() => {
        this.$refs.refTable.toggleRowSelection(row, false);
      });
    },

    submit() {
      this.$emit("submitTable", this.recordDataList);
      this.closeDialog();
    },
    closeDialog() {
      this.buildList = [];
      this.sysInstanceTotalPages = 10;
      this.sysInstanceIndex = 1;

      this.searchForm = {
        imei: "",
        buildingId: "",
      };

      this.recordDataList = [];
      this.$refs.refTable.clearSelection();
      this.dialogVisible = false;
    },
  },
};
</script>

<style scoped lang="less">
@import url("~@views/style/tablePage.less");
@import url("~@views/common.less");

.content-box {
  width: 100%;
  display: flex;
  //   justify-content: space-between;
  .container {
    // flex: 1;
    width: 47.6%;
    border: 1px solid #999;
    border-radius: 5px;
    .header {
      color: @primaryTxtcolor;
      padding: 0 20px;
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }
  .middle-icon {
    min-width: 40px;
    height: 40px;
    margin: 200px 5px 0;
    border-radius: 50%;
    background-color: @primaryBgcolor2;
    display: flex;
    align-items: center;
    justify-content: center;
    .el-icon-arrow-right {
      font-size: 20px;
      color: @primaryBorderColor2;
    }
  }
}
.tableBtnIcon {
  cursor: pointer;
}
</style>